clc;clear all;close all;
load('widebeamfactor.mat')
%% 参数设置
N = 16;              % 天线数
lambda = 1;         % 波长 (单位化)
d = lambda/2;       % 元间距
theta0_deg = 0;    % 期望波束指向角度 (度)
theta0 = deg2rad(theta0_deg);
%% 角度扫描
theta_scan_deg = -90:0.1:90;     % 扫描角度 (度)
theta_scan = deg2rad(theta_scan_deg);

%% 计算阵列因子
AF = zeros(size(theta_scan));
for idx = 1:length(theta_scan)
    theta = theta_scan(idx);
    a = exp(1*1j * pi * (0:N-1) * sin(theta)).';
    AF(idx) = BeamH'*a;
end

%% 归一化
AF_mag = abs(AF);
AF_mag_norm = AF_mag;

AF_dB_wide = 20*log10(AF_mag_norm);

%% 方向增益
G_max_dB_wide = AF_dB_wide((theta0_deg+90)/0.1+1);


%% 参数设置
N = 64;              % 天线数
lambda = 1;         % 波长 (单位化)
d = lambda/2;       % 元间距
theta0_deg = 30;    % 期望波束指向角度 (度)
theta0 = deg2rad(theta0_deg);

k = 2*pi/lambda;    % 波数

%% 角度扫描
theta_scan_deg = -90:0.1:90;     % 扫描角度 (度)
theta_scan = deg2rad(theta_scan_deg);

%% 计算阵列因子
AF = zeros(size(theta_scan));
for idx = 1:length(theta_scan)
    theta = theta_scan(idx);
    psi = k*d*(sin(theta) - sin(theta0));
    if abs(psi) < 1e-6
        AF(idx) = N;  % 避免 0/0
    else
        AF(idx) = sin(N*psi/2) / sin(psi/2);
    end
end

%% 不归一化
AF_mag = abs(AF);
AF_mag_norm = AF_mag;

AF_dB_narrow = 20*log10(AF_mag_norm);

%% 方向增益
G_max_dB_narrow = AF_dB_narrow((theta0_deg+90)/0.1+1);
%% 绘图
figure;hold on;
plot(theta_scan_deg, AF_dB_wide, 'LineWidth', 1.5);
plot(theta_scan_deg, AF_dB_narrow, 'LineWidth', 1.5);
xlabel('\theta (°)');
ylabel('Normalized Array Gain (dB)');
title(sprintf('ULA Direction Pattern with Beam Steering to %d°', theta0_deg));
grid on;
ylim([-40 40]);
xlim([-90 90]);
hold on;
line([theta0_deg theta0_deg], [-40 40], 'Color', 'r', 'LineStyle', '--');
text(theta0_deg+5, 15, sprintf('Beam at %d°',theta0_deg), 'Color', 'r');
text(-80, 35, sprintf('Wide Beam Direction Gain ≈ %.1f dB', G_max_dB_wide), 'FontSize',10,'Color','b');
text(-80, 30, sprintf('Narrow Beam Direction Gain ≈ %.1f dB', G_max_dB_narrow), 'FontSize',10,'Color','b');
legend('宽波束', '窄波束');
